<?php


namespace EchoPHP\Foundation\Support;

use EchoPHP\Http\Cookie;

class ResponseHeaderBag extends HeaderBag {

    const DISPOSITION_ATTACHMENT = 'attachment';
    const DISPOSITION_INLINE = 'inline';

    /**
     * 字符串形式
     */
    const COOKIES_FLAT = 'flat';
    /**
     * 数组形式
     */
    const COOKIES_ARRAY = 'array';

    protected $headerNames = [];
    protected $cookies = [];
    protected $computedCacheControl = [];

    public function __construct(array $headers = []) {
        $globalHeaders = app()->getGlobalHeaders();
        $headers = array_merge($globalHeaders, $headers);
        parent::__construct($headers);
        if (!isset($this->headers['cache-control'])) {
            $this->set('Cache-Control', '');
        }
        if (!isset($this->headers['date'])) {
            $this->initDate();
        }
    }

    /**
     * @see HeaderUtils::makeDisposition()
     */
    public function makeDisposition($disposition, $filename, $filenameFallback = '') {
        return HeaderUtils::makeDisposition((string)$disposition, (string)$filename, (string)$filenameFallback);
    }

    /**
     * 重置响应头信息
     * @param array $headers
     */
    public function replace(array $headers = []) {
        $this->headerNames = [];
        parent::replace($headers);
        if (!isset($this->headers['cache-control'])) {
            $this->set('Cache-Control', '');
        }
        if (!isset($this->headers['date'])) {
            $this->initDate();
        }
    }

    /**
     * 获取完整响应头信息
     * @return array
     */
    public function all() {
        $headers = parent::all();
        foreach ($this->getCookies() as $cookie) {
            $headers['set-cookie'][] = (string)$cookie;
        }
        return $headers;
    }

    /**
     * 设置一个响应头信息
     * @param $key
     * @param $value
     * @param bool $replace
     */
    public function set($key, $value, $replace = true) {
        $key = $this->getHeaderKey($key);
        if ('set-cookie' == $key) {
            if ($replace) {
                $this->cookies = [];
            }
            foreach ((array)$value as $cookie) {
                $this->setCookie(Cookie::fromString($cookie));
            }
            $this->headerNames[$key] = $key;
            return;
        }
        $this->headerNames[$key] = $key;

        parent::set($key, $value, $replace);

        // ensure the cache-control header has sensible defaults
        if (in_array($key, ['cache-control', 'etag', 'last-modified', 'expires'], true)) {
            $computed = $this->computeCacheControlValue();
            $this->headers['cache-control'] = [$computed];
            $this->headerNames['cache-control'] = 'Cache-Control';
            $this->computedCacheControl = $this->parseCacheControl($computed);
        }
    }

    /**
     * 移除一个响应头信息
     * @param $key
     */
    public function remove($key) {
        $key = $this->getHeaderKey($key);
        unset($this->headerNames[$key]);

        if ('set-cookie' == $key) {
            $this->cookies = [];
            return;
        }
        parent::remove($key);

        parent::remove($key);

        if ('cache-control' === $key) {
            $this->computedCacheControl = [];
        }

        if ('date' === $key) {
            $this->initDate();
        }
    }

    /**
     * 获取完整响应头信息
     * @return array
     */
    public function allPreserveCase() {
        $headers = [];
        foreach ($this->all() as $name => $value) {
            $name = isset($this->headerNames[$name]) ? $this->headerNames[$name] : $name;
            $headers[$name] = $value;
        }

        return $headers;
    }

    /**
     * 获取除cookie外的响应头信息
     * @return array
     */
    public function allPreserveCaseWithoutCookies() {
        $headers = $this->allPreserveCase();
        if (isset($this->headerNames['set-cookie'])) {
            unset($headers[$this->headerNames['set-cookie']]);
        }

        return $headers;
    }

    /**
     * 为响应头添加一个cookie信息
     * @param Cookie $cookie
     */
    public function setCookie(Cookie $cookie) {
        $this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie;
        $this->headerNames['set-cookie'] = 'Set-Cookies';
    }

    /**
     * 从响应头中删除一个cookie信息
     * @param $name
     * @param string $path
     * @param null $domain
     */
    public function removeCookie($name, $path = '/', $domain = null) {
        if (empty($path)) {
            $path = '/';
        }
        unset($this->cookies[$domain][$path][$name]);

        if (empty($this->cookies[$domain][$path])) {
            unset($this->cookies[$domain][$path]);

            if (empty($this->cookies[$domain])) {
                unset($this->cookies[$domain]);
            }
        }

        if (empty($this->cookies)) {
            unset($this->headerNames['set-cookie']);
        }
    }

    /**
     * 从响应头中清空一个cookie使其失效
     * @param $name
     * @param string $path
     * @param null $domain
     * @param bool $secure
     * @param bool $httpOnly
     */
    public function clearCookie($name, $path = '/', $domain = null, $secure = false, $httpOnly = true) {
        $this->setCookie(new Cookie($name, null, 1, $path, $domain, $secure, $httpOnly, false, null));
    }

    /**
     * 从响应头中获取完整cookie
     * @param string $format
     * @return array
     */
    public function getCookies($format = self::COOKIES_FLAT) {
        if (!in_array($format, [self::COOKIES_FLAT, self::COOKIES_ARRAY])) {
            $format = self::COOKIES_FLAT;
        }

        if (self::COOKIES_ARRAY == $format) {
            return $this->cookies;
        }

        $flattedCookies = [];
        foreach ($this->cookies as $path) {
            foreach ($path as $cookies) {
                foreach ($cookies as $cookie) {
                    $flattedCookies[] = $cookie;
                }
            }
        }
        return $flattedCookies;
    }

    /**
     * 整理cache-control信息字符串
     * @return string
     */
    protected function computeCacheControlValue() {
        if (!$this->cacheControl && !$this->has('ETag') && !$this->has('Last-Modified') && !$this->has('Expires')) {
            return 'no-cache, private';
        }

        if (!$this->cacheControl) {
            // conservative by default
            return 'private, must-revalidate';
        }

        $header = $this->getCacheControlHeader();
        if (isset($this->cacheControl['public']) || isset($this->cacheControl['private'])) {
            return $header;
        }

        // public if s-maxage is defined, private otherwise
        if (!isset($this->cacheControl['s-maxage'])) {
            return $header . ', private';
        }

        return $header;
    }

    /**
     * 设置响应头所需要的时间
     */
    private function initDate() {
        $now = \DateTime::createFromFormat('U', time());
        $now->setTimezone(new \DateTimeZone('UTC'));
        $this->set('Date', $now->format('D, d M Y H:i:s') . ' GMT');
    }
}